<script setup lang="ts" name="SystemErrorCodeForm">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { AreaApi } from '@/api/system/area'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const title = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  ip: '',
  result: ''
})
const formRules = reactive({
  ip: [{ required: true, message: t('sys.area.rules', 'ip'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async () => {
  visible.value = true
  title.value = t('sys.area', 'search')
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    formData.value.result = await AreaApi.getAreaByIp(formData.value.ip!.trim())
    message.success(t('sys.area', 'success'))
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    ip: '',
    result: ''
  }
  formRef.value?.resetFields()
}
</script>

<template>
  <Dialog v-model="visible" :title="title" width="600px">
    <el-form ref="formRef" v-loading="formLoading && systemConfig.loadingType === 'module'" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item :label="t('sys.area', 'ip')" prop="ip">
        <el-input v-model="formData.ip" clearable :placeholder="t('sys.area.rules', 'ip')" />
      </el-form-item>
      <el-form-item :label="t('sys.area', 'result')" prop="result">
        <el-input v-model="formData.result" clearable :placeholder="t('sys.area.rules', 'result')" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">
.el-form{
  margin-right: -6px;
}
</style>
